//
//  DR_SearchVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_SearchVC: DR_BaseVC {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        searchButton.addTarget(self, action: #selector(clickSearchButton), for: .touchUpInside)
        searchTextField.delegate = self
        
        // 监听输入框内容变化，实现实时搜索
        searchTextField.addTarget(self, action: #selector(searchTextFieldDidChange), for: .editingChanged)
        
        // 初始化时加载所有文件
        loadAllFiles()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 每次显示时刷新文件列表
        loadAllFiles()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 不自动聚焦搜索框，避免键盘弹出
    }
    
    private func setupUI(){
        view.addSubview(backButton)
        view.addSubview(searchContainerView)
        view.addSubview(filterContainerView)
        view.addSubview(tableView)
        
        searchContainerView.addSubview(searchIconView)
        searchContainerView.addSubview(searchTextField)
        searchContainerView.addSubview(searchButton)
        
        // 添加筛选按钮
        filterButtons.forEach { button in
            filterContainerView.addSubview(button)
            button.addTarget(self, action: #selector(filterButtonTapped(_:)), for: .touchUpInside)
        }
        
        // 设置 TableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(DR_SearchFileCell.self, forCellReuseIdentifier: DR_SearchFileCell.identifier)
    }
    
    @objc private func clickBackButton() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickSearchButton() {
        searchTextField.resignFirstResponder()
        performSearch()
    }
    
    @objc private func searchTextFieldDidChange() {
        // 实时搜索
        performSearch()
    }
    
    @objc private func filterButtonTapped(_ sender: UIButton) {
        // 更新选中状态
        selectedFilterIndex = sender.tag
        updateFilterButtons()
        
        // 执行搜索和筛选
        performSearch()
    }
    
    // MARK: - 加载所有文件
    private func loadAllFiles() {
        allFiles = DR_FileManager.shared.getAllFiles()
        performSearch()
    }
    
    // MARK: - 执行搜索和筛选
    private func performSearch() {
        let searchText = searchTextField.text?.trimmingCharacters(in: .whitespaces) ?? ""
        
        // 先根据筛选类型过滤
        var filteredFiles = allFiles
        if selectedFilterIndex > 0 {
            // 0=All, 1=PDF, 2=Word, 3=Excel, 4=PPT
            let filterTypes: [DR_FileType] = [.pdf, .word, .excel, .ppt]
            let selectedType = filterTypes[selectedFilterIndex - 1]
            filteredFiles = allFiles.filter { $0.fileType == selectedType }
        }
        
        // 再根据搜索关键词过滤（模糊搜索）
        if !searchText.isEmpty {
            filteredFiles = filteredFiles.filter { file in
                // 模糊匹配文件名（不区分大小写）
                file.fileName.localizedCaseInsensitiveContains(searchText) ||
                file.displayName.localizedCaseInsensitiveContains(searchText)
            }
        }
        
        // 转换为DR_SearchFileModel
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        fileList = filteredFiles.map { file in
            let dateString = dateFormatter.string(from: file.createDate)
            return DR_SearchFileModel(
                fileName: file.fileName,
                date: dateString,
                size: file.fileSizeString,
                isFavorite: DR_FileManager.shared.isFavorite(file),
                fileType: file.fileType.rawValue
            )
        }
    }
    
    // MARK: - 处理重命名
    private func handleRenameFile(_ fileModel: DR_SearchFileModel) {
        // 从文件列表中查找对应的DR_FileModel
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == fileModel.fileName }) else {
            view.makeToast("无法找到对应的文件", duration: 2.0, position: .center)
            return
        }
        
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: matchingFile.displayName)
        
        renameSheet.onConfirm = { [weak self] newName in
            guard let self = self else { return }
            
            // 根据文件类型调用不同的重命名方法
            if matchingFile.fileType == .pdf {
                if let _ = DR_PDFTool.shared.renamePDF(oldFileURL: matchingFile.fileURL, newName: newName) {
                    // 重新加载文件列表并执行搜索
                    self.loadAllFiles()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            } else {
                // 其他文件类型的重命名
                if let _ = self.renameFile(oldFileURL: matchingFile.fileURL, newName: newName) {
                    // 重新加载文件列表并执行搜索
                    self.loadAllFiles()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            }
        }
        
        renameSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    // MARK: - 重命名文件（通用）
    private func renameFile(oldFileURL: URL, newName: String) -> URL? {
        let fileExtension = oldFileURL.pathExtension
        let sanitizedName = sanitizeFileName(newName)
        let newURL = oldFileURL.deletingLastPathComponent().appendingPathComponent("\(sanitizedName).\(fileExtension)")
        
        // 检查新文件名是否已存在
        if FileManager.default.fileExists(atPath: newURL.path) {
            return nil
        }
        
        // 重命名文件
        do {
            try FileManager.default.moveItem(at: oldFileURL, to: newURL)
            return newURL
        } catch {
            print("❌ [DR_SearchVC] 文件重命名失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    // MARK: - 清理文件名
    private func sanitizeFileName(_ fileName: String) -> String {
        let invalidChars = CharacterSet(charactersIn: "/\\?%*|\"<>")
        return fileName.components(separatedBy: invalidChars).joined(separator: "_")
    }
    
    
    // MARK: - 处理删除
    private func handleDeleteFile(_ fileModel: DR_SearchFileModel) {
        // 从文件列表中查找对应的DR_FileModel
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == fileModel.fileName }) else {
            view.makeToast("无法找到对应的文件", duration: 2.0, position: .center)
            return
        }
        
        let deleteSheet = DR_DeleteConfirmSheet()
        
        deleteSheet.onDelete = { [weak self] in
            guard let self = self else { return }
            do {
                // 删除前先移除收藏
                DR_FileManager.shared.removeFavorite(matchingFile)
                try FileManager.default.removeItem(at: matchingFile.fileURL)
                // 重新加载文件列表并执行搜索
                self.loadAllFiles()
                self.view.makeToast("del_succ".localized, duration: 2.0, position: .center)
            } catch {
                self.view.makeToast("del_error".localized, duration: 2.0, position: .center)
            }
        }
        
        deleteSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            deleteSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            deleteSheet.show(in: tabBarController.view)
        } else {
            deleteSheet.show(in: view)
        }
    }
    
    // MARK: - 处理显示详情
    private func handleShowDetails(_ fileModel: DR_SearchFileModel) {
        // 从文件列表中查找对应的DR_FileModel
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == fileModel.fileName }) else {
            view.makeToast("无法找到对应的文件", duration: 2.0, position: .center)
            return
        }
        
        let detailsSheet = DR_FileDetailsSheet()
        detailsSheet.configure(with: matchingFile)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            detailsSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            detailsSheet.show(in: tabBarController.view)
        } else {
            detailsSheet.show(in: view)
        }
    }
    
    // MARK: - 处理分享
    private func handleShareFile(_ fileModel: DR_SearchFileModel) {
        // 从文件列表中查找对应的DR_FileModel以获取fileURL
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == fileModel.fileName }) else {
            print("无法找到对应的文件: \(fileModel.fileName)")
            return
        }
        
        let activityVC = UIActivityViewController(activityItems: [matchingFile.fileURL], applicationActivities: nil)
        
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
    
    // MARK: - 处理收藏切换
    private func handleToggleFavorite(_ fileModel: DR_FileModel) {
        let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
        // 刷新文件列表以更新收藏状态
        loadAllFiles()
        if isNowFavorite {
            view.makeToast("collect_succ".localized, duration: 2.0, position: .center)
        } else {
            view.makeToast("collect_error".localized, duration: 2.0, position: .center)
        }
    }
    
    // MARK: - 处理锁定/解锁PDF
    private func handleLockPDF(_ fileModel: DR_FileModel) {
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // 已设置密码，先验证密码再解锁
            let passwordSheet = DR_EnterPasswordSheet()
            
            // 配置文件信息
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                
                // 验证密码
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    // 密码正确，移除密码
                    if DR_PDFTool.shared.removePassword(for: fileModel.fileURL) {
                        sheet.hide()
                        self.view.makeToast("密码已移除", duration: 2.0, position: .center)
                    } else {
                        self.view.makeToast("操作失败", duration: 2.0, position: .center)
                    }
                } else {
                    // 密码错误，显示错误信息（不关闭弹窗）
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // 未设置密码，显示设置密码弹窗
            let passwordSheet = DR_SetPasswordSheet()
            
            passwordSheet.onConfirm = { [weak self] password in
                guard let self = self else { return }
                if DR_PDFTool.shared.setPassword(for: fileModel.fileURL, password: password) {
                    self.view.makeToast("密码设置成功", duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("密码设置失败", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        }
    }
    
    // MARK: - 处理Merge PDF
    private func handleMergePDF() {
        let selVC = DR_SelectVC()
        selVC.type = 1
        pushHidingTabBar(selVC, animated: true)
    }
    
    // MARK: - 处理Split PDF
    private func handleSplitPDF(_ fileModel: DR_FileModel) {
        // 检查PDF是否被锁定
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // PDF已锁定，需要先输入密码
            let passwordSheet = DR_EnterPasswordSheet()
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    sheet.hide()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        self.openSplitPDFVC(fileModel.fileURL)
                    }
                } else {
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {}
            
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // PDF未锁定，直接打开Split页面
            openSplitPDFVC(fileModel.fileURL)
        }
    }
    
    private func openSplitPDFVC(_ fileURL: URL) {
        let splitVC = DR_SplitPDFVC(pdfFileURL: fileURL)
        pushHidingTabBar(splitVC, animated: true)
    }
    
    private func showMoreActionSheet(for fileModel: DR_SearchFileModel) {
        let actionSheet = DR_FileMoreActionSheet()
        
        // 从文件列表中查找对应的DR_FileModel
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == fileModel.fileName }) else {
            view.makeToast("无法找到对应的文件", duration: 2.0, position: .center)
            return
        }
        
        // 根据文件类型决定显示哪些操作
        var actions: [DR_FileMoreAction] = []
        
        // PDF 特有操作
        if matchingFile.fileType == .pdf {
            actions.append(DR_FileMoreAction(title: "home_merge".localized, iconName: "more_merge", action: { [weak self] in
                self?.handleMergePDF()
            }))
            actions.append(DR_FileMoreAction(title: "home_split".localized, iconName: "more_split", action: { [weak self] in
                self?.handleSplitPDF(matchingFile)
            }))
            
            // 根据是否已设置密码显示不同的操作
            let lockTitle = DR_PDFTool.shared.hasPassword(for: matchingFile.fileURL) ? "Unlock PDF" : "home_lock".localized
            actions.append(DR_FileMoreAction(title: lockTitle, iconName: "more_lock", action: { [weak self] in
                self?.handleLockPDF(matchingFile)
            }))
        }
        
        // 通用操作
        actions.append(DR_FileMoreAction(title: "more_rename".localized, iconName: "more_rename", shouldAutoHide: false, action: { [weak self, unowned actionSheet] in
            actionSheet.hide()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self?.handleRenameFile(fileModel)
            }
        }))
        
        // 根据收藏状态设置不同的标题和图标
        let isFavorite = DR_FileManager.shared.isFavorite(matchingFile)
        let favoriteTitle = isFavorite ? "more_collected".localized : "more_collection".localized
        let favoriteIcon = isFavorite ? "home_collected" : "home_collect"
        actions.append(DR_FileMoreAction(title: favoriteTitle, iconName: favoriteIcon, action: { [weak self] in
            self?.handleToggleFavorite(matchingFile)
        }))
        
        actions.append(DR_FileMoreAction(title: "more_share".localized, iconName: "more_share", action: { [weak self] in
            self?.handleShareFile(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_details".localized, iconName: "more_detail", action: { [weak self] in
            self?.handleShowDetails(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_delete".localized, iconName: "more_del", action: { [weak self] in
            self?.handleDeleteFile(fileModel)
        }))
        
        actionSheet.configure(with: fileModel, actions: actions)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            actionSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            actionSheet.show(in: tabBarController.view)
        } else {
            actionSheet.show(in: view)
        }
    }
    
    private func updateFilterButtons() {
        for (index, button) in filterButtons.enumerated() {
            if index == selectedFilterIndex {
                // 选中状态：蓝色背景，白色文字
                button.backgroundColor = "#333FFF".toColor
                button.setTitleColor(.white, for: .normal)
            } else {
                // 未选中状态：浅灰色背景，灰色文字
                button.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
                button.setTitleColor(UIColor.gray, for: .normal)
            }
        }
    }
    
    private func setupConstraints(){
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        
        searchContainerView.snp.makeConstraints { make in
            make.leading.equalTo(backButton.snp.trailing)
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(backButton)
            make.height.equalTo(44)
        }
        
        searchIconView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        searchTextField.snp.makeConstraints { make in
            make.leading.equalTo(searchIconView.snp.trailing).offset(8)
            make.trailing.equalTo(searchButton.snp.leading).offset(-8)
            make.centerY.equalToSuperview()
            make.height.equalTo(36)
        }
        
        searchButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
            make.width.equalTo(60)
            make.height.equalTo(36)
        }
        
        filterContainerView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(25)
            make.top.equalTo(backButton.snp.bottom).offset(15)
            make.height.equalTo(20)
        }
        
        // 筛选按钮布局
        let buttonWidth = (UIScreen.main.bounds.width - 50 - 4 * 35) / 5 // 总宽度减去左右边距和按钮间距，除以5
        
        for (index, button) in filterButtons.enumerated() {
            button.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat(index) * (buttonWidth + 35))
                make.top.bottom.equalToSuperview()
                make.width.equalTo(buttonWidth)
            }
        }
        
        tableView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(filterContainerView.snp.bottom).offset(16)
        }
    }

    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("common_back".toImage, for: .normal)
        return v
    }()
    
    private let searchContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = "#F6F7FF".toColor
        view.layer.cornerRadius = 18
        return view
    }()
    
    private let searchIconView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "folder-search")
        imageView.contentMode = .scaleAspectFit
        imageView.tintColor = UIColor.gray
        return imageView
    }()
    
    private let searchTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "search_title".localized
        textField.font = UIFont.systemFont(ofSize: 15)
        textField.textColor = .black
        textField.returnKeyType = .search
        textField.clearButtonMode = .whileEditing
        textField.autocorrectionType = .no
        textField.autocapitalizationType = .none
        return textField
    }()
    
    private let searchButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("search_search".localized, for: .normal)
        button.setTitleColor("#333FFF".toColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        return button
    }()
    
    private let filterContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    private var selectedFilterIndex: Int = 0
    
    private lazy var filterButtons: [UIButton] = {
        let titles = ["All", "PDF", "Word", "Excel", "PPT"]
        return titles.enumerated().map { index, title in
            let button = UIButton(type: .custom)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            button.layer.cornerRadius = 10
            button.tag = index
            
            // 初始状态：第一个按钮选中
            if index == 0 {
                button.backgroundColor = "#F4F5FF".toColor
                button.setTitleColor("#333FFF".toColor, for: .normal)
            } else {
                button.backgroundColor = "#F4F5FF".toColor
                button.setTitleColor("#B5B5B5".toColor, for: .normal)
            }
            
            return button
        }
    }()
    
    private let tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.rowHeight = 72
        return tableView
    }()
    
    // 所有文件列表
    private var allFiles: [DR_FileModel] = []
    
    // 搜索和筛选后的文件列表
    private var fileList: [DR_SearchFileModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
}

// MARK: - UITextFieldDelegate
extension DR_SearchVC: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 点击键盘上的搜索按钮时执行搜索
        clickSearchButton()
        return true
    }
}

// MARK: - UITableViewDataSource, UITableViewDelegate
extension DR_SearchVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fileList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DR_SearchFileCell.identifier, for: indexPath) as! DR_SearchFileCell
        let model = fileList[indexPath.row]
        cell.configure(with: model)
        
        cell.onFavoriteTapped = { [weak self] in
            guard let self = self else { return }
            let model = self.fileList[indexPath.row]
            // 从文件列表中查找对应的DR_FileModel
            let allFiles = DR_FileManager.shared.getAllFiles()
            if let matchingFile = allFiles.first(where: { $0.fileName == model.fileName }) {
                let isNowFavorite = DR_FileManager.shared.toggleFavorite(matchingFile)
                // 更新文件列表中的收藏状态
                var updatedModel = self.fileList[indexPath.row]
                updatedModel.isFavorite = isNowFavorite
                self.fileList[indexPath.row] = updatedModel
                cell.configure(with: updatedModel)
            }
        }
        
        cell.onMoreTapped = { [weak self] in
            self?.showMoreActionSheet(for: model)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let model = fileList[indexPath.row]
        
        // 从文件列表中查找对应的DR_FileModel
        let allFiles = DR_FileManager.shared.getAllFiles()
        guard let matchingFile = allFiles.first(where: { $0.fileName == model.fileName }) else {
            return
        }
        
        // 根据文件类型打开预览
        if matchingFile.fileType == .pdf {
            // PDF 文件使用 DR_LookPDFVC 预览
            // 检查PDF是否被锁定
            if DR_PDFTool.shared.hasPassword(for: matchingFile.fileURL) {
                // PDF已锁定，需要先输入密码
                showPasswordInputForPDF(matchingFile)
            } else {
                // PDF未锁定，直接进入预览
                openPDFPreview(matchingFile)
            }
        } else {
            // Word、Excel、PPT 文件使用 DR_LookFileVC 预览
            let previewVC = DR_LookFileVC()
            previewVC.configure(with: matchingFile)
            pushHidingTabBar(previewVC, animated: true)
        }
    }
    
    // MARK: - 显示PDF密码输入弹窗
    private func showPasswordInputForPDF(_ fileModel: DR_FileModel) {
        let passwordSheet = DR_EnterPasswordSheet()
        
        // 配置文件信息
        passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            
            // 验证密码
            if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                // 密码正确，关闭弹窗并进入预览
                sheet.hide()
                // 等待弹窗隐藏动画完成后再push
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.openPDFPreview(fileModel, isPasswordVerified: true)
                }
            } else {
                // 密码错误，显示错误信息（不关闭弹窗）
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    // MARK: - 打开PDF预览
    private func openPDFPreview(_ fileModel: DR_FileModel, isPasswordVerified: Bool = false) {
        let pdfModel = DR_PDFFileModel(
            fileName: fileModel.fileName,
            fileURL: fileModel.fileURL,
            fileSize: fileModel.fileSize,
            createDate: fileModel.createDate,
            pageCount: fileModel.pageCount
        )
        let previewVC = DR_LookPDFVC()
        previewVC.configure(with: pdfModel, isPasswordVerified: isPasswordVerified)
        pushHidingTabBar(previewVC, animated: true)
    }
}
